package cn.itcast.service.impl;

import cn.itcast.mapper.ClazzMapper;
import cn.itcast.mapper.EmpMapper;
import cn.itcast.mapper.StudentMapper;
import cn.itcast.pojo.*;
import cn.itcast.service.ClazzService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private EmpMapper empMapper;

    @Override
    public Result addClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        save(clazz);
        return Result.success("添加成功");

        /*clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        System.out.println(clazz);
        int clazzes = clazzMapper.addClazz(clazz);

        return clazzes > 0 ? Result.success("添加成功", clazzes) : Result.error("添加失败");*/

    }

    /**
     * 分页查询
     *
     * @param name
     * @param beginDate
     * @param endDate
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Result findAll(String name, LocalDate beginDate, LocalDate endDate, Integer page, Integer pageSize) {
        //1.使用MyBatisPlus技术实现分页查询
        //2.调用分页方法
        Page<Clazz> clazzPage = Page.of(page, pageSize);
        LambdaQueryWrapper<Clazz> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like((name != null && !name.isEmpty()), Clazz::getName, name)
                .eq(beginDate != null, Clazz::getBeginDate, beginDate)
                .eq(endDate != null, Clazz::getEndDate, endDate);
        clazzPage = page(clazzPage, queryWrapper);
        //3.获取总数量和结果
        List<Clazz> clazzes = clazzPage.getRecords();
        long total = clazzPage.getTotal();
        //4.需要将班主任设置进去
        //4.1获取到emp表的数据(根据clazz表的班主任id)
        LambdaQueryWrapper<Emp> lambdaQuery = Wrappers.lambdaQuery();
        List<Integer> list = new ArrayList<>();
        clazzes.forEach(clazz -> {
            list.add(clazz.getMasterId());
        });
        lambdaQuery.in(Emp::getId, list);
        List<Emp> emps = empMapper.selectList(lambdaQuery);

        clazzes.forEach(clazz -> {
            emps.stream().filter(emp -> emp.getId().equals(clazz.getMasterId())).findFirst()
                    .ifPresent(emp -> clazz.setMasterName(emp.getName()));
            clazz.setStatus(clazz.getEndDate().isBefore(LocalDate.now()) ? "已结课" : "在读");
        });
        return Result.success("分页查询成功", new PageResult<Clazz>(total, clazzes));

        /*//1.使用分页助手(会帮我们计算总的数量)
        PageHelper.startPage(page, pageSize);
        List<Clazz> clazzes = clazzMapper.findAll(name, beginDate, endDate);
        //2.使用page类型进行强转
        Page<Clazz> p = (Page<Clazz>) clazzes;
        LocalDate nowTime = LocalDate.now();//当前时间
        //拿到开课时间和节课时间
        for (Clazz clazz1 : p) {
            LocalDate startTime = clazz1.getBeginDate();
            LocalDate endTime = clazz1.getEndDate();
            //4.判断状态
            if (nowTime.isBefore(startTime)) {
                p.forEach(clazz -> clazz1.setStatus("未开课"));
            } else if (nowTime.isAfter(endTime)) {
                p.forEach(clazz -> clazz1.setStatus("已结课"));
            } else {
                p.forEach(clazz -> clazz1.setStatus("在读"));
            }
        }

        //3.拿到总数量和数据
        long total = p.getTotal();
        List<Clazz> list = p.getResult();
        //4.封装一下
        PageResult<Clazz> clazzPageResult = new PageResult<>(total, list);
        return Result.success("分页查询成功", clazzPageResult);*/
    }


    @Override
    public Result deleteById(Integer id) {
        LambdaQueryWrapper<Student> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Student::getClazzId, id);
        Long count = studentMapper.selectCount(queryWrapper);
        if (count > 0) {
            //说明班级下面有学生,所以不能删除
            return Result.error("班级下有学生,不能删除");
        }
        clazzMapper.deleteById(id);
        return Result.success("删除成功");
        /*//1.根据班级id查询学生表统计数量
        Integer count = studentMapper.selectByIdCount(id);
        if (count == 0) {
            clazzMapper.deleteById(id);
            return Result.success("删除成功");
        } else {
            return Result.error("班级下有学生,不能删除");
        }*/

    }

    @Override
    public Result selectById(Integer id) {
        LambdaQueryWrapper<Clazz> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Clazz::getId, id);
        Clazz one = getOne(queryWrapper);
        /*Clazz clazzes = clazzMapper.selectById(id);
        return clazzes != null ? Result.success("查询成功", clazzes) : Result.error("查询失败");*/
        return Result.success("查询成功", one);
    }

    @Override
    public Result update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        updateById(clazz);
       /* clazz.setUpdateTime(LocalDateTime.now());
        int row = clazzMapper.update(clazz);

        return row > 0 ? Result.success("修改成功") : Result.error("修改失败");*/
        return Result.success("修改成功");
    }

    @Override
    public Result searchAll() {
        List<Clazz> clazzes = clazzMapper.selectList(null);
        /*List<Clazz> clazzes = clazzMapper.searchAll();*/

        return clazzes != null ? Result.success("查询成功", clazzes) : Result.error("查询失败");

    }


}
